package com.qf.leadnewswemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.leadnewscommon.minio.MinioOperator;
import com.qf.leadnewsmodel.dtos.ResponseResult;
import com.qf.leadnewsmodel.enums.AppHttpCodeEnum;
import com.qf.leadnewsutils.commons.ThreadLocalUtil;
import com.qf.leadnewswemedia.mapper.WmMaterialMapper;
import com.qf.leadnewswemedia.model.pojos.WmMaterial;
import com.qf.leadnewswemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinioOperator minioOperator;

    @Override
    public ResponseResult uploadPic(MultipartFile multipartFile) throws Exception {

        //判断是否登录
        Long uid = ThreadLocalUtil.getUid();
        if (uid == null || uid == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (multipartFile == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取上传的图片原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");  //abc.png
        String suffix = i==-1?"":originalFilename.substring(i);
        //生成唯一文件名
        String filename = UUID.randomUUID().toString().replaceAll("-","")+suffix;

        InputStream is = multipartFile.getInputStream();
        //将图片上传到minio中
        String url = minioOperator.uploadImage(is, filename);

        if (url == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.MATERIASL_UPLOAD_FAIL);
        }else{
            //保存数据库
            WmMaterial material = new WmMaterial();
            material.setUrl(url);
            material.setUserId(Integer.parseInt(uid+""));
            material.setType((short) 0);
            material.setIsCollection((short) 0);
            material.setCreatedTime(new Date());

            save(material);

            //返回前端数据
            return ResponseResult.okResult(material);
        }
    }
}
